#!/usr/bin/env node

// 命令行curl -X POST -d "name=lisi$age=20" http://localhost:8080

// 引入所需的模块
const http = require('http');
const url = require('url');

// 确保有命令行参数
if (process.argv.length !== 3) {
  console.log('Usage: node 03-post.js "data"');
  process.exit(1);
}

// 解析命令行参数
const postData = process.argv[2];

// 解析 URL
const parsedUrl = url.parse('http://localhost:8080');

// 设置请求选项
const options = {
  hostname: parsedUrl.hostname,
  port: parsedUrl.port,
  path: parsedUrl.path,
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

// 发起请求
const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);

  // 接收响应数据
  res.setEncoding('utf8');
  let responseString = '';
  res.on('data', (chunk) => {
    responseString += chunk;
  });
  res.on('end', () => {
    console.log('BODY:\n', responseString);
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// 写入数据到请求体
req.write(postData);
req.end();